package com.niuxiaofa.newlaw.Base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.jaeger.library.StatusBarUtil;
import com.niuxiaofa.newlaw.R;
import com.niuxiaofa.newlaw.Tools.ActivityUtil;
import com.niuxiaofa.newlaw.Tools.UIUtils;
import com.niuxiaofa.newlaw.View.LoadingDialog;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.ButterKnife;


/**
 * Created by gxjkz on 2017/7/25.
 */

public abstract class BaseActivity extends AppCompatActivity {
    private static Context context;
    public Activity activity;

    private LoadingDialog loadingDialog;

    public RefreshLayout refreshLayout;
    public RefreshInterface refreshinterface;
    TextView title;
    /**
     * 日志输出标志
     **/
    protected final String TAG = this.getClass().getSimpleName();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        activity = this;
        ActivityUtil.getInstance().addActivity(this);

      //  hideBottomUIMenu();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initState();
        //隐藏状态栏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        //默认不弹出系统键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        setSystemInvadeBlack(true);
        setStatusColor();//状态栏颜色

        setContentView(getLayoutId());
        ButterKnife.bind(this);

        this.loadingDialog = new LoadingDialog(this);
        this.loadingDialog.setCanceledOnTouchOutside(false);
//        mediaPlayer = MediaPlayer.create(getContext(), R.raw.volume_sound);




        ImageView return_back = (ImageView) findViewById(R.id.return_back);

        if (return_back != null) {
            return_back.setOnClickListener(e -> {
                 ActivityUtil.getInstance().finishCurrentActivity();
            });
        }

        title = (TextView) findViewById(R.id.common_toolbar_title);
        try {

            refreshLayout = findViewById(R.id.refreshLayout);
            if (refreshLayout != null&&refreshinterface!=null) {
                refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                    @Override
                    public void onRefresh(RefreshLayout refreshlayout) {
                        refreshinterface.refresh.refresh();
                    }
                });
                refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(RefreshLayout refreshlayout) {
                        refreshinterface.refresh.loadmore();
                    }
                });

            }
        }catch (Exception e){

        }
        initData();


    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    public void setTitle(String titleText) {

        if (title != null) {
            title.setText(titleText);
        }

    }


    public Activity getActivity() {

        return activity;
    }

    /**
     * 判断是否是快速点击
     */
    private static long lastClickTime;

    public static Context getContext() {
        return context;
    }


    protected abstract int getLayoutId();


//    @Override
//    public void setRequestedOrientation(int requestedOrientation) {
//        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    protected void setStatusColor() {
        StatusBarUtil.setTransparent(this);
    }

    public void setActivity(Activity activity) {
        if (activity != null)
            this.activity = activity;
    }


    public void Toast(String content) {
        Toast.makeText(UIUtils.getContext(), content, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);   //this

        FragmentManager fragmentManager = this.getSupportFragmentManager();
        if (fragmentManager.getFragments() == null)

            return;

        for (int indext = 0; indext < fragmentManager.getFragments().size(); indext++) {
            Fragment fragment = fragmentManager.getFragments().get(indext); //找到第一层Fragment
            if (fragment == null)
                Log.w("onActivityResult", "Activity result no fragment exists for index: 0x"
                        + Integer.toHexString(requestCode));
            else
                handleResult(fragment, requestCode, resultCode, data);
        }
    }

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        times = 0;
//        return super.dispatchTouchEvent(ev);
//    }

    /**
     * 给Fragment传递参数
     * 递归调用，对所有的子Fragment生效
     *
     * @param fragment
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void handleResult(Fragment fragment, int requestCode, int resultCode, Intent data) {
        fragment.onActivityResult(requestCode, resultCode, data);//调用每个Fragment的onActivityResult
        List<Fragment> childFragment = fragment.getChildFragmentManager().getFragments(); //找到第二层Fragment
        if (childFragment != null)
            for (Fragment f : childFragment)
                if (f != null) {
                    handleResult(f, requestCode, resultCode, data);
                }
    }


    private static boolean isExit = false;
    private long mExitTime;


    /**
     * 程序退出
     */
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(UIUtils.getActivity(), "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
           // ActivityCollector.removeAllActivity();//结束程序
        }
    }

    protected abstract void initData();

    public void dismissDialog() {
        if (this.loadingDialog.isShowing()) {
            this.loadingDialog.dismiss();
        }
    }

    public void showLoadingDialog() {
        showLoadingDialog(true);
    }

    public void showLoadingDialog(String str, boolean z) {
        if (!this.loadingDialog.isShowing()) {
            this.loadingDialog.setCancelable(z);
            this.loadingDialog.show();
            this.loadingDialog.setText(str);
        }
    }

    public void showLoadingDialog(boolean z) {
        showLoadingDialog("加载中...", z);
    }


//    /*Session启动、App使用时长等基础数据统计接口API*/
//    @Override
//    public void onResume() {
//        super.onResume();
//        MobclickAgent.onResume(UIUtils.getActivity());
//    }
//
//
//    @Override
//    public void onPause() {
//        super.onPause();
//        MobclickAgent.onPause(UIUtils.getActivity());
//    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityUtil.getInstance().removeActivity(this);
    }

//    /**
//     * 点击非编辑区域收起键盘
//     * 获取点击事件
//     */
//    @CallSuper
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            View view = getCurrentFocus();
//            if (isShouldHideKeyBord(view, ev)) {
//                hideSoftInput(view.getWindowToken());
//            }
//        }
//        return super.dispatchTouchEvent(ev);
//    }
//
//    /**
//     * 判定当前是否需要隐藏
//     */
//    protected boolean isShouldHideKeyBord(View v, MotionEvent ev) {
//        if (v != null && (v instanceof EditText)) {
//            int[] l = {0, 0};
//            v.getLocationInWindow(l);
//            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
//            return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
//            //return !(ev.getY() > top && ev.getY() < bottom);
//        }
//        return false;
//    }
//
//    /**
//     * 隐藏软键盘
//     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (checkDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    protected void setSystemInvadeBlack(Boolean isblack) {
        // 第二个参数是是否沉浸,第三个参数是状态栏字体是否为黑色。
        if (isblack) {
            StatusBarUtil.setLightMode(this);
        } else {
            StatusBarUtil.setDarkMode(this);
        }

    }

    public static boolean checkDoubleClick() {
        //点击时间
        long clickTime = SystemClock.uptimeMillis();
        //如果当前点击间隔小于500毫秒
        if (lastClickTime >= clickTime - 500) {
            return true;
        }
        //记录上次点击时间
        lastClickTime = clickTime;
        return false;

    }
}